﻿// Define a blackberry viewport
Ext.define('Ext.viewport.Blackberry', {
    extend: 'Ext.viewport.Default',
    constructor: function(config) {
        // Blackberry does not like height: 100%   
        this.superclass.config.height = this.getWindowHeight() + 'px';
        this.callParent([config]);
        return this;
    },
    getWindowHeight: function() {
        if (Ext.os.version.lt('7.0')) {
            return window.innerHeight;
        }
        else {
            // OS7 needs more browser height ONLY when running in webworks.
            return window.innerHeight + 42;
        }
    }

}, function() {

});


// Insert a new Blackberry specific viewport
Ext.override(Ext.viewport.Viewport,
{
    constructor: function(config) {
        var osName = Ext.os.name,
            viewportName, viewport;
        switch (osName) {
            case 'Android':
                viewportName = 'Android';
                break;
            case 'BlackBerry':
                viewportName = 'Blackberry';
                break;
            case 'iOS':
                viewportName = 'Ios';
                break;
            default:
                viewportName = 'Default';
        }
        viewport = Ext.create('Ext.viewport.' + viewportName, config);
        return viewport;
    }
});

Ext.application({
    name: 'LibOC',

    launch: function()
    {
        //window.localStorage.clear();

        Ext.regModel('ordenCompraModel',
        {
            idProperty: 'id',
            fields: [
                { name: 'Id', type: 'string' },
                { name: 'PO', type: 'string' },
                { name: 'Sociedad', type: 'string' },
                { name: 'OrgCompras', type: 'string' },
                { name: 'CondPago', type: 'string' },
                { name: 'CondPagoT', type: 'string' },
                { name: 'ClaseDoc', type: 'string' },
                { name: 'ClaseDocT', type: 'string' },
                { name: 'GrpCompras', type: 'string' },
                { name: 'Moneda', type: 'string' },
                { name: 'TipoCambio', type: 'float' },
                { name: 'CodProveedor', type: 'string' },
                { name: 'DescProveedor', type: 'string' },
                { name: 'Fecha', type: 'string' },
                { name: 'TotNeto', type: 'float' },
                { name: 'TotBruto', type: 'float' },
                { name: 'LibGrp', type: 'string' },
                { name: 'LibEst', type: 'string' },
                { name: 'LibInd', type: 'string' },
                { name: 'LibCod', type: 'string' },
                { name: 'NomSoc', type: 'string' },
                { name: 'NomCrea', type: 'string' },
                { name: 'Telefono', type: 'string' },
                { name: 'CodUsuario', type: 'string' },
                { name: 'NomSolicitante', type: 'string' },
                { name: 'DesUsuario', type: 'string' },
                { name: 'Items', type: 'array' },
                { name: 'Contactos', type: 'array' },
                { name: 'Solicitantes', type: 'array' },
                { name: 'Texto', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'ordenCompraStore'
            }
        });

        Ext.regModel('itemModel',
        {
            fields: [
                { name: 'PO', type: 'string' },
                { name: 'Pos', type: 'string' },
                { name: 'NroOrd', type: 'string' },
                { name: 'ActFijo', type: 'string' },
                { name: 'CentCO', type: 'string' },
                { name: 'NombRespCO', type: 'string' },
                { name: 'Solicitante', type: 'string' },
                { name: 'Cod', type: 'string' },
                { name: 'Desc', type: 'string' },
                { name: 'UM', type: 'string' },
                { name: 'Cant', type: 'float' },
                { name: 'Precio', type: 'float' },
                { name: 'Total', type: 'float' },
                { name: 'Moneda', type: 'string' },
                { name: 'DescCentCO', type: 'string' },
                { name: 'DescNroOrd', type: 'string' },
                { name: 'CodProveedor', type: 'string' },
                { name: 'DesProveedor', type: 'string' },
                { name: 'TipoImputacion', type: 'string' },
                { name: 'MotivoBloqueoPos', type: 'string' },
                { name: 'CodigoLiberacion', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'itemStore'
            }
        });

        Ext.regModel('contactoModel',
        {
            fields: [
                { name: 'LIFNR', type: 'string' },
                { name: 'NAME_TEXT', type: 'string' },
                { name: 'TEL_NUMBER', type: 'string' },
                { name: 'TEL_EXTENS', type: 'string' },
                { name: 'MOB_NUMBER', type: 'string' },
                { name: 'SMTP_ADDR', type: 'string' },
                { name: 'DEPARTMENT', type: 'string' },
                { name: 'FUNCTION', type: 'string' },
                { name: 'BNAME', type: 'string' },
                { name: 'STREET', type: 'string' },
                { name: 'POST_CODE1', type: 'string' },
                { name: 'CITY1', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'contactoStore'
            }
        });

        Ext.regModel('accesoModel',
        {
            fields: [
                { name: 'servidor', type: 'string' },
                { name: 'nombre', type: 'string' },
                { name: 'puerto', type: 'string' },
                { name: 'protocolo', type: 'string' },
                { name: 'hostValue', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'accesoStore'
            }
        });

        Ext.regModel('solicitanteModel',
        {
            fields: [
                { name: 'LIFNR', type: 'string' },
                { name: 'NAME_TEXT', type: 'string' },
                { name: 'TEL_NUMBER', type: 'string' },
                { name: 'TEL_EXTENS', type: 'string' },
                { name: 'MOB_NUMBER', type: 'string' },
                { name: 'SMTP_ADDR', type: 'string' },
                { name: 'DEPARTMENT', type: 'string' },
                { name: 'FUNCTION', type: 'string' },
                { name: 'BNAME', type: 'string' },
                { name: 'STREET', type: 'string' },
                { name: 'POST_CODE1', type: 'string' },
                { name: 'CITY1', type: 'string' }
            ],

            proxy: {
                type: 'localstorage',
                id: 'solicitanteStore'
            }
        });

        Ext.regModel('SAPUserBE',
        {
            fields: [
                { name: 'Id', type: 'string' },
                { name: 'Uname', type: 'string' },
                { name: 'Passwd', type: 'string' },
                { name: 'Mandt', type: 'string' },
                { name: 'Server', type: 'string' },
                { name: 'SapRouter', type: 'string' },
                { name: 'Langu', type: 'string' },
                { name: 'Instance', type: 'string' },
                { name: 'SysId', type: 'string' }
            ],

            validations: [
                { type: 'presence', field: 'Uname', message: 'Debe ingresar nombre de usuario' },
                { type: 'presence', field: 'Passwd', message: 'Debe ingresar clave de acceso' },
                { type: 'presence', field: 'Langu', message: 'Debe seleccionar el idioma' }
            ]
        });

        Ext.regStore('ordenCompraStore2',
        {
            autoLoad: true,
            model: 'ordenCompraModel'
        });

        Ext.regStore('ordenCompraStore',
        {
            autoLoad: true,
            model: 'ordenCompraModel'
        });

        Ext.regStore('itemStore',
        {
            autoLoad: true,
            model: 'itemModel'
        });

        Ext.regStore('contactoStore',
        {
            autoLoad: true,
            model: 'contactoModel'
        });

        Ext.regStore('solicitanteStore',
        {
            autoLoad: true,
            model: 'solicitanteModel'
        });

        Ext.regStore('accesoStore',
        {
            autoLoad: true,
            model: 'accesoModel'
        });

        Ext.regStore('SAPUserStore',
        {
            proxy: new Ext.data.LocalStorageProxy(
	        {
	            id: 'SAPUserStore',
	            proxy:
		        {
		            idProperty: 'SAPUserStore'
		        }
	        }),
            model: 'SAPUserBE',
            autoLoad: true,
            autoSave: true
        });

        var solicitanteOC = new Ext.form.FormPanel({
            id: 'solicitanteOC',
            items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                cls: 'x-toolbar-title',
                title: 'Creado por',
                items: [
                {
                    xtype: 'button',
                    text: 'Volver',
                    ui: 'back',
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        panelPrincipal.animateActiveItem(detalleOC, { type: 'slide', direction: 'right' });
                    }
                },
                {
                    xtype: 'spacer'
}]
                },
            {
                xtype: 'panel',
                layout: 'hbox',
                items: [
                {
                    xtype: 'panel',
                    flex: 1,
                    styleHtmlContent: true,
                    html: [
                        '<div align="center"><img src="resources/img/contact.png" width="48" heigth="48"/></div>'
                    ]
                },
                {
                    xtype: 'dataview',
                    store: 'solicitanteStore',
                    flex: 1,
                    styleHtmlContent: true,
                    itemTpl: [
                        '<div class="textoContacto">{NAME_TEXT}<br />' +
                        '{FUNCTION}<br />' +
                        '{DEPARTMENT}</div>',
                    ]
}]
                },
            {
                xtype: 'fieldset',
                title: 'Información del Creador',
                defaults:
            	{
            	    labelWidth: '35%'
            	},
                items: [
                {
                    xtype: 'urlfield',
                    label: 'Teléfono',
                    name: 'TEL_NUMBER',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele)
                        {
                            var nombre = solicitanteOC.getRecord().data.NAME_TEXT;
                            var nro = solicitanteOC.getRecord().data.TEL_NUMBER;
                            if (nro)
                            {
                                Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res)
                                {
                                    if (res == 'si')
                                    {
                                        window.location = 'tel:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Extensión',
                    name: 'TEL_EXTENS',
                    readOnly: true
                },
                {
                    xtype: 'urlfield',
                    label: 'Móvil',
                    name: 'MOB_NUMBER',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele)
                        {
                            var nombre = solicitanteOC.getRecord().data.NAME_TEXT;
                            var nro = solicitanteOC.getRecord().data.MOB_NUMBER;
                            if (nro)
                            {
                                Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res)
                                {
                                    if (res == 'si')
                                    {
                                        window.location = 'tel:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                },
                {
                    xtype: 'urlfield',
                    label: 'Correo',
                    name: 'SMTP_ADDR',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele)
                        {
                            var nombre = solicitanteOC.getRecord().data.NAME_TEXT;
                            var nro = solicitanteOC.getRecord().data.SMTP_ADDR;
                            if (nro)
                            {
                                Ext.Msg.confirm('Contacto', 'Enviar correo a ' + nombre + "?", function(res)
                                {
                                    if (res == 'si')
                                    {
                                        window.location = 'mailto:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
}]
                },
            {
                xtype: 'fieldset',
                title: 'Compañia',
                defaults:
            	{
            	    labelWidth: '35%'
            	},
                items: [
                {
                    xtype: 'textareafield',
                    label: 'Dirección',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele)
                        {
                            var record = solicitanteOC.getRecord();
                            ele.setValue(record.data.STREET + '\n' + record.data.CITY1 + '\n' + record.data.POST_CODE1);
                        }
                    }
}]
}]
            });

            var contactoOC = new Ext.form.FormPanel({
                id: 'contactoOC',
                items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                cls: 'x-toolbar-title',
                title: 'Proveedor',
                items: [
                {
                    xtype: 'button',
                    text: 'Volver',
                    ui: 'back',
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        panelPrincipal.animateActiveItem(itemOC, { type: 'slide', direction: 'right' });
                    }
                },
                {
                    xtype: 'spacer'
}]
                },
            {
                xtype: 'panel',
                layout: 'hbox',
                items: [
                {
                    xtype: 'panel',
                    flex: 1,
                    styleHtmlContent: true,
                    html: [
                        '<div align="center"><img src="resources/img/contact.png" width="48" heigth="48"/></div>'
                    ]
                },
                {
                    xtype: 'dataview',
                    cls: 'twitterView',
                    store: 'contactoStore',
                    flex: 1,
                    styleHtmlContent: true,
                    itemTpl: [
                        '<div class="textoContacto">{NAME_TEXT}<br />' +
                        '{FUNCTION}<br />' +
                        '{DEPARTMENT}</div>',
                   ]
}]
                },
            {
                xtype: 'fieldset',
                title: 'Información del Proveedor',
                defaults:
            	{
            	    labelWidth: '35%'
            	},
                items: [
                {
                    xtype: 'urlfield',
                    label: 'Teléfono',
                    name: 'TEL_NUMBER',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele)
                        {
                            var nombre = contactoOC.getRecord().data.NAME_TEXT;
                            var nro = contactoOC.getRecord().data.TEL_NUMBER;
                            if (nro)
                            {
                                Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res)
                                {
                                    if (res == 'si')
                                    {
                                        window.location = 'tel:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Extensión',
                    name: 'TEL_EXTENS',
                    readOnly: true
                },
                {
                    xtype: 'urlfield',
                    label: 'Móvil',
                    name: 'MOB_NUMBER',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele)
                        {
                            var nombre = contactoOC.getRecord().data.NAME_TEXT;
                            var nro = contactoOC.getRecord().data.MOB_NUMBER;
                            if (nro)
                            {
                                Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res)
                                {
                                    if (res == 'si')
                                    {
                                        window.location = 'tel:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
                },
                {
                    xtype: 'urlfield',
                    label: 'Correo',
                    name: 'SMTP_ADDR',
                    readOnly: true,
                    listeners: {
                        'focus': function(ele)
                        {
                            var nombre = contactoOC.getRecord().data.NAME_TEXT;
                            var nro = contactoOC.getRecord().data.SMTP_ADDR;
                            if (nro)
                            {
                                Ext.Msg.confirm('Contacto', 'Enviar correo a ' + nombre + "?", function(res)
                                {
                                    if (res == 'si')
                                    {
                                        window.location = 'mailto:' + nro;
                                    }
                                }, this);
                            }
                        }
                    }
}]
                },
            {
                xtype: 'fieldset',
                title: 'Compañia',
                defaults:
            	{
            	    labelWidth: '35%'
            	},
                items: [
                {
                    xtype: 'textareafield',
                    label: 'Dirección',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele)
                        {
                            var record = contactoOC.getRecord();
                            ele.setValue(record.data.STREET + '\n' + record.data.CITY1 + '\n' + record.data.POST_CODE1);
                        }
                    }
}]
}]
            });

            var itemOC = new Ext.form.FormPanel({
                id: 'itemOC',
                items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                cls: 'x-toolbar-title',
                title: 'Posición',
                items: [
                {
                    xtype: 'button',
                    text: 'Volver',
                    ui: 'back',
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        panelPrincipal.animateActiveItem(detalleOC, { type: 'slide', direction: 'right' });
                    }
                },
                {
                    xtype: 'spacer'
}]
                },
            {
                xtype: 'fieldset',
                title: 'Datos de Posición',
                defaults:
    	        {
    	            labelWidth: '35%'
    	        },
                items: [
                {
                    xtype: 'textfield',
                    label: 'Nro. de Pos.',
                    name: 'Pos',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Cantidad',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele)
                        {
                            var record = itemOC.getRecord();
                            ele.setValue(record.data.Cant + ' ' + record.data.UM);
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Precio Unit.',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele)
                        {
                            var record = itemOC.getRecord();
                            ele.setValue(record.data.Precio + ' ' + record.data.Moneda);
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'CeCo',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele)
                        {
                            var record = itemOC.getRecord();
                            ele.setValue(record.data.CentCO + ' - ' + record.data.DescCentCO);
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Responsable CO',
                    name: 'NombRespCO',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Orden',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele)
                        {
                            var record = itemOC.getRecord();
                            ele.setValue(record.data.NroOrd + ' - ' + record.data.DescNroOrd);
                        }
                    }
                },
                {
                    xtype: 'textfield',
                    label: 'Activo Fijo',
                    name: 'ActFijo',
                    readOnly: true
}]
                },
            {
                xtype: 'fieldset',
                title: 'Proveedor',
                defaults:
    	        {
    	            labelWidth: '35%'
    	        },
                items: [
                {
                    xtype: 'textfield',
                    label: 'Nombre',
                    readOnly: true,

                    listeners: {
                        'painted': function(ele)
                        {
                            var rec = itemOC.getRecord().data.CodProveedor;
                            var sto = Ext.getStore('contactoStore');
                            var contacto = sto.findRecord('LIFNR', rec);
                            if (contacto)
                            {
                                ele.setValue(contacto.data.NAME_TEXT);
                            }
                        },
                        'focus': function(ele)
                        {
                            console.log("prueba");
                            var rec = itemOC.getRecord().data.CodProveedor;
                            var sto = Ext.getStore('contactoStore');
                            var contacto = sto.findRecord('LIFNR', rec);
                            if (contacto)
                            {
                                var SAPUserStore = Ext.getStore('SAPUserStore');
                                validateUser(SAPUserStore); //validar login de usuario
                                contactoOC.setRecord(contacto);
                                contactoOC.items.items[1].items.items[1].refresh();
                                panelPrincipal.animateActiveItem(contactoOC, { type: 'slide', direction: 'left' });
                            }
                        }
                    }
}]
                },
            {
                xtype: 'toolbar',
                id: 'tbLiberar',
                cls: 'x-toolbar-title',
                docked: 'bottom',
                items: [
                {
                    xtype: 'button',
                    text: 'Liberar',
                    id: 'btnLiberar',
                    ui: 'confirm',
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        //                        panelFloat.showBy(detalleOC.getComponent('tbLiberar').getComponent('btnLiberar'));
                        //---------------------------------------------------
                        Ext.Viewport.setMasked({
                            xtype: 'loadmask',
                            message: 'Conectando ...'
                        });
                        var LibCod = itemOC.getRecord().data.CodigoLiberacion;
                        var SP = itemOC.getRecord().data.PO;
                        var Pos = itemOC.getRecord().data.Pos;
                        var sto = Ext.getStore('accesoStore');
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        var host = sto.last().data.hostValue;
                        itemOC.add({ xtype: 'hiddenfield', id: 'LibCod', name: 'LibCod', value: LibCod });
                        itemOC.add({ xtype: 'hiddenfield', id: 'Posicion', name: 'Posicion', value: Pos });
                        itemOC.add({ xtype: 'hiddenfield', id: 'SP', name: 'SP', value: SP });
                        itemOC.add({ xtype: 'hiddenfield', id: 'Header', name: 'Header', value: 'I' });
                        prepareForm(itemOC, SAPUserStore); //@@@
                        itemOC.submit({
                            method: 'POST',
                            url: host + '/release.aspx',
                            success: function(form, action)
                            {
                                Ext.Viewport.setMasked(false);
                                if (action.success)
                                {
                                    Ext.Msg.alert('Aviso', action.errors.reason);
                                    panelFloat.hide();
                                    var sto = listaOC.getStore().data.items;
                                    for (var i = 0; i < sto.length; i++)
                                    {
                                        var currentPO = sto[i];
                                        if (currentPO.data.PO == SP)
                                        {
                                            listaOC.getStore().remove(currentPO);
                                            listaOC.getStore().sync();
                                            listaOC.refresh();
                                            var items = itemOC.items.items;
                                            for (var i = 0; i < items.length; i++)
                                            {
                                                var currentItem = items[i];
                                                if (currentItem.id = 'SP')
                                                {
                                                    itemOC.remove(currentItem);
                                                }
                                                if (currentItem.id = 'Posicion')
                                                {
                                                    itemOC.remove(currentItem);
                                                }
                                                if (currentItem.id = 'LibCod')
                                                {
                                                    itemOC.remove(currentItem);
                                                }
                                            }
                                            panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                                        }
                                    }
                                }
                                else
                                {
                                    Ext.Msg.alert('Error', action.errors.reason);
                                }
                            },
                            failure: function(form, action)
                            {
                                Ext.Viewport.setMasked(false);
                                if (action.errors)
                                {
                                    Ext.Msg.alert('Error', action.errors.reason);
                                }
                                else
                                {
                                    Ext.Msg.alert('Error', 'Status: ' + action.status + ' - ' + action.statusText);
                                }
                            }
                        });
                    }
                },
                {
                    xtype: 'spacer'
                },
                {
                    xtype: 'button',
                    text: 'Cancelar',
                    ui: 'decline',
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });

                    }
}]
}]
            });

            var form = new Ext.form.FormPanel({
                id: 'form',
                items: [
            {
                xtype: 'fieldset',
                items: [
                {
                    xtype: 'button',
                    text: 'Liberar',
                    ui: 'action',
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        Ext.Viewport.setMasked({
                            xtype: 'loadmask',
                            message: 'Conectando ...'
                        });
                        var listaitemsSP = [];
                        for (var j = 0; j < detalleOC.getRecord().data.Items.length; j++)
                        {
                            listaitemsSP.push(detalleOC.getRecord().data.Items[j]);
                        }
                        var listaitemsSPJson = JSON.stringify(listaitemsSP);
                        var sto = Ext.getStore('accesoStore');
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        var host = sto.last().data.hostValue;
                        form.add({ xtype: 'hiddenfield', id: 'Header', name: 'Header', value: 'H' });
                        form.add({ xtype: 'hiddenfield', id: 'itemsSP', name: 'itemsSP', value: listaitemsSPJson });
                        prepareForm(form, SAPUserStore); //@@@
                        form.submit({
                            method: 'POST',
                            url: host + '/release.aspx',
                            success: function(form, action)
                            {
                                Ext.Viewport.setMasked(false);
                                if (action.success)
                                {
                                    Ext.Msg.alert('Aviso', action.errors.reason);
                                    panelFloat.hide();
                                    var sto = listaOC.getStore().data.items;
                                    for (var i = 0; i < sto.length; i++)
                                    {
                                        var currentPO = sto[i];
                                        if (currentPO.data.PO == PO)
                                        {
                                            listaOC.getStore().remove(currentPO);
                                            listaOC.getStore().sync();
                                            listaOC.refresh();
                                            panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                                        }
                                    }
                                }
                                else
                                {
                                    Ext.Msg.alert('Error', action.errors.reason);
                                }
                            },
                            failure: function(form, action)
                            {
                                Ext.Viewport.setMasked(false);
                                if (action.errors)
                                {
                                    Ext.Msg.alert('Error', action.errors.reason);
                                }
                                else
                                {
                                    Ext.Msg.alert('Error', 'Status: ' + action.status + ' - ' + action.statusText);
                                }
                            }
                        });
                    }
                },
                {
                    xtype: 'button',
                    text: 'Cancelar',
                    ui: 'normal',
                    handler: function()
                    {
                        panelFloat.hide();
                    }
}]
}]
            });

            var panelFloat = new Ext.Panel({
                id: 'panelFloat',
                layout: 'fit',
                centered: true,
                modal: true,
                hidden: true,
                hideOnMaskTap: true,
                width: 200,
                height: 70,
                items: [form]
            });

            var detalleOC = new Ext.form.FormPanel({
                id: 'detalleOC',
                scrollable: {
                    direction: 'vertical',
                    directionLock: true
                },
                items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                title: 'Detalle',
                cls: 'x-toolbar-title',
                items: [
                {
                    xtype: 'button',
                    text: 'Volver',
                    ui: 'back',
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                    }
                },
                {
                    xtype: 'spacer'
}]
                },
            {
                xtype: 'fieldset',
                title: 'Datos',
                items: [
                {
                    xtype: 'textfield',
                    label: 'Nro. Doc.',
                    name: 'PO',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Tipo Doc.',
                    name: 'ClaseDocT',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Sociedad',
                    name: 'NomSoc',
                    readOnly: true
                },
                {
                    xtype: 'textfield',
                    label: 'Monto Total',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele)
                        {
                            var record = detalleOC.getRecord();
                            ele.setValue(record.data.TotBruto + ' ' + record.data.Moneda);
                        }
                    }
                },
                {
                    xtype: 'textareafield',
                    label: 'Texto',
                    name: 'Texto',
                    readOnly: true
}]
                },
            {
                xtype: 'fieldset',
                title: 'Creado por',
                items: [
                {
                    xtype: 'textfield',
                    label: 'Nombre',
                    readOnly: true,
                    listeners: {
                        'painted': function(ele)
                        {
                            var record = detalleOC.getRecord();
                            ele.setValue(record.data.NomSolicitante);
                        },
                        'focus': function(ele)
                        {
                            var rec = detalleOC.getRecord().data.CodUsuario;
                            var sto = Ext.getStore('solicitanteStore');
                            var solicitante = sto.findRecord('BNAME', rec);
                            if (solicitante)
                            {
                                var SAPUserStore = Ext.getStore('SAPUserStore');
                                validateUser(SAPUserStore); //validar login de usuario
                                solicitanteOC.setRecord(solicitante);
                                solicitanteOC.items.items[1].items.items[1].refresh();
                                panelPrincipal.animateActiveItem(solicitanteOC, { type: 'slide', direction: 'left' });
                            }
                        }
                    }
}]
                },
            {
                xtype: 'fieldset',
                title: 'Productos',
                items: [
                {
                    xtype: 'list',
                    store: 'itemStore',
                    scrollable: {
                        disabled: true
                    },
                    allowDeselect: true,
                    itemTpl:
                    '<div class="getAutoHeight">' +
                    '<div class="doc-img"><img src="resources/img/item.png" width="20" height="20">' +
                    '</div>' +
                    '<div class="list-list">' +
                        '<div style="font-weight:bold">{Desc}</div>' +
                    '{Cant} {UM}&nbsp;x&nbsp;{Precio}&nbsp;{Moneda}' +
	                '<br />' +
	                '{Total}&nbsp;{Moneda}' +
	                '</div>' +
                    '<div class="doc-img2"><img src="resources/img/arrow.png" width="20" height="20">' +
                    '</div>',
                    height: 200,
                    listeners: {
                        itemtap: function(list, item, index, record)
                        {
                            var SAPUserStore = Ext.getStore('SAPUserStore');
                            validateUser(SAPUserStore); //validar login de usuario
                            //---------------------------------------------------
                            itemOC.reset();
                            itemOC.setRecord(record);
                            itemOC.items.items[0].setTitle('Posición ' + ltrim(record.data.Pos));
                            itemOC.items.items[1].setTitle(record.data.Desc);
                            panelPrincipal.animateActiveItem(itemOC, { type: 'slide', direction: 'left' });
                        }
                    }
}]
                },
            {
                xtype: 'toolbar',
                id: 'tbLiberar',
                cls: 'x-toolbar-title',
                docked: 'bottom',
                items: [
                {
                    xtype: 'button',
                    text: 'Liberar',
                    id: 'btnLiberarHeader',
                    ui: 'confirm',
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        panelFloat.showBy(detalleOC.getComponent('tbLiberar').getComponent('btnLiberarHeader'));
                    }
                },
                {
                    xtype: 'spacer'
                },
                {
                    xtype: 'button',
                    text: 'Cancelar',
                    ui: 'decline',
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                    }
}]
}]
            });

            var listaOC = new Ext.dataview.List({
                id: 'listaOC',
                store: 'ordenCompraStore',
                allowDeselect: true,
                loadingText: "Cargando Solicitudes...",
                itemTpl:
            '<div class="getAutoHeight">' +
            '<div class="doc-img"><img src="resources/img/shopping_cart.png" width="30" height="30">' +
            '</div>' +
            '<div class="list-doci">' +
                '<div style="font-weight:bold;">{PO}</div>' +
            '{NomSolicitante}&nbsp;&nbsp;' +
            '</div>' +
            '<div class="list-docd">' +
                '<div style="font-weight:bold;">{TotBruto}&nbsp;&nbsp;{Moneda}</div>' +
            '{Fecha}' +
            '</div>' +
            '<div class="doc-img2"><img src="resources/img/arrow.png" width="20" height="20">' +
            '</div>',
                listeners: {
                    itemtap: function(list, item, index, record)
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        detalleOC.setRecord(record);
                        var PO = record.data.PO;
                        var sto = Ext.getStore('itemStore');
                        sto.getProxy().clear();
                        sto.data.clear();
                        sto.sync();
                        sto.add(record.data.Items);
                        sto.sync();
                        var sto = Ext.getStore('contactoStore');
                        sto.getProxy().clear();
                        sto.data.clear();
                        sto.sync();
                        sto.add(record.data.Contactos);
                        sto.sync();
                        var sto = Ext.getStore('solicitanteStore');
                        sto.getProxy().clear();
                        sto.data.clear();
                        sto.sync();
                        sto.add(record.data.Solicitantes);
                        sto.sync();
                        var sto = Ext.getStore('ordenCompraStore2');
                        sto.getProxy().clear();
                        sto.data.clear();
                        sto.sync();
                        sto.add(record);
                        sto.sync();
                        detalleOC.items.items[3].items.items[0].refresh();
                        detalleOC.items.items[0].setTitle('Sol. Pedido');
                        panelPrincipal.animateActiveItem(detalleOC, { type: 'slide', direction: 'left' });
                    }
                }
            });

            var listaOCPanel = new Ext.form.FormPanel({
                id: 'listaOCPanel',
                layout: 'fit',
                items: [
            {
                xtype: 'toolbar',
                title: 'Lista',
                cls: 'x-toolbar-title',
                docked: 'top',
                items: [
	            {
	                xtype: 'button',
	                ui: 'decline',
	                text: 'Salir',
	                handler: function()
	                {
	                    window.localStorage.clear();
	                    loginForm.reset();
	                    panelPrincipal.animateActiveItem(loginForm, { type: 'slide', direction: 'right' });
	                }
	            },
	            {
	                xtype: 'spacer'
}]
            },
            listaOC,
            {
                xtype: 'toolbar',
                cls: 'x-toolbar-title-small',
                docked: 'bottom',
                items: [
                {
                    xtype: 'button',
                    ui: 'confirm',
                    iconCls: 'refresh',
                    iconMask: true,
                    handler: function()
                    {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        //---------------------------------------------------
                        Ext.Viewport.setMasked({
                            xtype: 'loadmask',
                            message: 'Conectando ...'
                        });
                        var sto = Ext.getStore('accesoStore');
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        var host = sto.last().data.hostValue;
                        prepareForm(listaOCPanel, SAPUserStore); //@@@
                        listaOCPanel.submit({
                            method: 'POST',
                            url: host + '/List.aspx',
                            success: function(form, action)
                            {
                                Ext.Viewport.setMasked(false);
                                if (action.success)
                                {
                                    listaOC.getStore().getProxy().clear();
                                    listaOC.getStore().data.clear();
                                    listaOC.getStore().sync();
                                    listaOC.refresh();
                                    listaOC.getStore().add(action.lstItemsResale);
                                    listaOC.getStore().sync();
                                    var now = new Date();
                                    listaOCPanel.items.items[2].setTitle('Actualizado  al ' + now.getDate() + '.' + (now.getMonth() + 1) + '.' + now.getFullYear() + '  ' + now.getHours() + ':' + now.getMinutes());
                                }
                                else
                                {
                                    Ext.Msg.alert('Error', action.errors.reason);
                                }
                            },
                            failure: function(form, action)
                            {
                                Ext.Viewport.setMasked(false);
                                //Falta manejo de error por timeout
                                if (action.errors)
                                {
                                    Ext.Msg.alert('Error', action.errors.reason);
                                }
                                else
                                {
                                    Ext.Msg.alert('Error', 'Status: ' + action.status + ' - ' + action.statusText);
                                }
                            }
                        });
                    }
                },
	            {
	                xtype: 'spacer'
	            },
                {
                    xtype: 'spacer'
}]
}]
            });

            var accesoForm = new Ext.form.FormPanel({
                scroll: 'vertical',
                items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                cls: 'x-toolbar-title',
                title: 'Accesos'
            },
        	{
        	    xtype: 'toolbar',
        	    cls: 'x-toolbar-title',
        	    docked: 'bottom',
        	    items: [
        	    {
        	        xtype: 'button',
        	        text: 'Volver',
        	        ui: 'dark',
        	        handler: function()
        	        {
        	            panelPrincipal.animateActiveItem(loginForm, { type: 'slide', direction: 'left' });
        	        }
        	    },
	            {
	                xtype: 'spacer'
	            },
	            {
	                xtype: 'button',
	                text: 'Grabar',
	                ui: 'confirm',
	                handler: function()
	                {
	                    var ser = accesoForm.getValues().servidor;
	                    var nom = accesoForm.getValues().nombre;
	                    var pue = accesoForm.getValues().puerto;
	                    var pro = accesoForm.getValues().protocolo;
	                    if (ser == '' && nom == '' && pue == '' && pro == '')
	                    {
	                        Ext.Msg.alert("Aviso", 'Verifique los campos ingresados');
	                    }
	                    else
	                    {
	                        accesoForm.reset();
	                        hostValue(ser, nom, pue, pro, panelPrincipal);
	                    }
	                }
}]
        	},
        	{
        	    xtype: 'fieldset',
        	    title: 'Parámetros conexión al sistema.',
        	    items: [
        		{
        		    xtype: 'textfield',
        		    label: 'Servidor de aplicación',
        		    name: 'servidor',
        		    listeners: {
        		        'painted': function(ele)
        		        {
        		            var sto = Ext.getStore('accesoStore');
        		            var rec = sto.last();
        		            if (rec)
        		            {
        		                ele.setValue(rec.data.servidor);
        		            }
        		        }
        		    }
        		},
        		{
        		    xtype: 'textfield',
        		    label: 'Nombre de la aplicación',
        		    name: 'nombre',
        		    listeners: {
        		        'painted': function(ele)
        		        {
        		            var sto = Ext.getStore('accesoStore');
        		            var rec = sto.last();
        		            if (rec)
        		            {
        		                ele.setValue(rec.data.nombre);
        		            }
        		        }
        		    }
        		},
        		{
        		    xtype: 'textfield',
        		    label: 'Puerto',
        		    name: 'puerto',
        		    listeners: {
        		        'painted': function(ele)
        		        {
        		            var sto = Ext.getStore('accesoStore');
        		            var rec = sto.last();
        		            if (rec)
        		            {
        		                ele.setValue(rec.data.puerto);
        		            }
        		        }
        		    }
        		},
        		{
        		    xtype: 'textfield',
        		    label: 'Protocolo',
        		    name: 'protocolo',
        		    listeners: {
        		        'painted': function(ele)
        		        {
        		            var sto = Ext.getStore('accesoStore');
        		            var rec = sto.last();
        		            if (rec)
        		            {
        		                ele.setValue(rec.data.protocolo);
        		            }
        		        }
        		    }
}]
}]
            });

            var loginForm = new Ext.form.FormPanel({
                id: 'loginForm',
                scroll: 'vertical',
                items: [
            {
                xtype: 'fieldset',
                title: nombreEmpresa
            },
            {
                xtype: 'fieldset',
                items: [
	            {
	                xtype: 'textfield',
	                id: 'usuario',
	                name: 'usuario',
	                label: 'Usuario',
	                useClearIcon: true,
	                required: true,
	                value: ''
	            },
	            {
	                xtype: 'passwordfield',
	                id: 'clave',
	                name: 'clave',
	                label: 'Clave',
	                useClearIcon: true,
	                required: true,
	                value: ''
}]
            },
            {
                xtype: 'fieldset',
                hidden: true,
                items: [
	            {
	                xtype: 'selectfield',
	                id: 'idioma',
	                name: 'idioma',
	                label: 'Idioma',
	                options: [
		            {
		                text: 'Español',
		                value: 'ES'
}]
}]
            },
            {
                xtype: 'toolbar',
                cls: 'x-toolbar-title',
                docked: 'bottom',
                items: [
	            {
	                xtype: 'button',
	                text: 'Accesos',
	                ui: 'dark',
	                handler: function()
	                {
	                    var sto = Ext.getStore('accesoStore');
	                    var rec = sto.last();
	                    if (rec)
	                    {
	                        if (rec.data.servidor == defServidor && rec.data.nombre == defNombre && rec.data.puerto == defPuerto && rec.data.protocolo == defProtocolo)
	                        {
	                            sto.getProxy().clear();
	                            sto.data.clear();
	                            sto.sync();
	                        }
	                    }
	                    panelPrincipal.animateActiveItem(accesoForm, { type: 'slide', direction: 'right' });
	                }
	            },
	            {
	                xtype: 'spacer'
	            },
	            {
	                xtype: 'button',
	                text: 'Entrar',
	                ui: 'confirm',
	                handler: function()
	                {
	                    var sto = Ext.getStore('accesoStore');
	                    if (!sto.last())
	                    {//cargar accesos por default
	                        hostValue(defServidor, defNombre, defPuerto, defProtocolo, 'loginForm');
	                    }
	                    var host = sto.last().data.hostValue;
	                    var loUser = Ext.ModelMgr.create({
	                        Uname: loginForm.getValues().usuario,
	                        Passwd: loginForm.getValues().clave,
	                        Langu: loginForm.getValues().idioma
	                    }, 'SAPUserBE');
	                    var errors = loUser.validate();
	                    var message = "";
	                    if (!errors.isValid())
	                    {
	                        errors.each(function(item, index, length)
	                        {
	                            message += item.getMessage() + "<br>";
	                        });
	                        Ext.Msg.alert("Error", message, function() { });
	                        return false;
	                    }
	                    Ext.Viewport.setMasked({
	                        xtype: 'loadmask',
	                        message: 'Conectando ...'
	                    });
	                    loginForm.submit({
	                        method: 'POST',
	                        url: host + '/login.aspx',
	                        success: function(form, action)
	                        {
	                            Ext.Viewport.setMasked(false);
	                            if (!action) { Ext.Msg.alert('Error', 'Verifique los parámetros de acceso'); }
	                            else
	                            {
	                                if (action.success)
	                                {
	                                    var SAPUserStore = Ext.getStore('SAPUserStore');
	                                    var loUser = new SAPUserBE(action.user);
	                                    SAPUserStore.add(loUser);
	                                    SAPUserStore.sync();
	                                    listaOC.getStore().getProxy().clear();
	                                    listaOC.getStore().data.clear();
	                                    listaOC.getStore().sync();
	                                    listaOC.refresh();
	                                    listaOC.getStore().add(action.lstItemsResale);
	                                    listaOC.getStore().sync();
	                                    var now = new Date();
	                                    listaOCPanel.items.items[2].setTitle('Actualizado  al ' + now.getDate() + '.' + (now.getMonth() + 1) + '.' + now.getFullYear() + '  ' + now.getHours() + ':' + now.getMinutes());
	                                    panelPrincipal.animateActiveItem(listaOCPanel, { type: 'slide', direction: 'left' });
	                                }
	                                else
	                                {
	                                    Ext.Msg.alert('Error', action.errors.reason);
	                                }
	                            }
	                        },
	                        failure: function(form, action)
	                        {
	                            Ext.Viewport.setMasked(false);
	                            if (!action.errors || !action.errors.reason)
	                            { Ext.Msg.alert('Error', 'Verifique los parámetros de acceso'); }
	                            else
	                            {
	                                Ext.Msg.alert('Error', action.errors.reason);
	                            }
	                        }
	                    });
	                }
}]
}]
            });

            var panelPrincipal = new Ext.Panel({
                id: 'panelPrincipal',
                fullscreen: true,
                layout: 'card',
                cardAnimation: 'slide',
                items: [loginForm, accesoForm, listaOCPanel, detalleOC, itemOC, contactoOC, solicitanteOC]
            });

            Ext.Viewport.add(panelPrincipal);
        }
    });